{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:55.903667Z",
     "start_time": "2018-09-04T07:51:55.330648Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import random as rn\n",
    "\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(12345)\n",
    "\n",
    "tf.set_random_seed(1234)\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "import pickle\n",
    "\n",
    "Path = 'D:\\\\APViaML'\n",
    "\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)\n",
    "\n",
    "\n",
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "\n",
    "def creat_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    '''\n",
    "    Data providing function:\n",
    "\n",
    "    This function is separated from model() so that hyperopt\n",
    "    won't reload data for each evaluation run.\n",
    "    '''\n",
    "    traindata_startyear_str = str(1958) \n",
    "    traindata_endyear_str = str(num + 1987) \n",
    "    vdata_startyear_str = str(num + 1976) \n",
    "    vdata_endyear_str = str(num + 1987) \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "  \n",
    "    X_traindata =  np.array(df_X.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    Y_traindata = np.array(df_Y.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    X_vdata = np.array(df_X.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    Y_vdata = np.array(df_Y.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "        \n",
    "    return X_traindata, Y_traindata, X_vdata, Y_vdata, X_testdata, Y_testdata\n",
    "\n",
    "\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:46:33.059635Z",
     "start_time": "2018-09-04T12:46:32.580866Z"
    }
   },
   "outputs": [],
   "source": [
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "del data\n",
    "\n",
    "def creat_test_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "    return X_testdata, Y_testdata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:46:37.302391Z",
     "start_time": "2018-09-04T12:46:37.295874Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_model_pre(model_name):\n",
    "    Y_pre_list_final= []\n",
    "    test_performance_score_list = []\n",
    "    for i in range(30):\n",
    "        X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "        model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "        file = open(model_filepath,'rb')\n",
    "        best_model = pickle.load(file)\n",
    "        file.close()        \n",
    "        Y_pre_list =best_model.predict(X_testdata)\n",
    "        test_score = Evaluation_fun(Y_pre_list, Y_testdata)\n",
    "        for x in Y_pre_list:\n",
    "            Y_pre_list_final.append(x)        \n",
    "        test_performance_score_list.append(test_score)\n",
    "    return Y_pre_list_final,test_performance_score_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.450623Z",
     "start_time": "2018-09-04T07:51:56.446611Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_pre_list(model_name):\n",
    "    model_filepath = Path + '\\\\output\\\\data\\\\Model_' + model_name+'_Top1000_Prediction.pkl'\n",
    "    file = open(model_filepath,'rb')\n",
    "    pre_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return pre_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## load each model prediction "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.472682Z",
     "start_time": "2018-09-04T07:51:56.453129Z"
    }
   },
   "outputs": [],
   "source": [
    "OLS_pre_list = get_pre_list(model_name='OLS')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.490228Z",
     "start_time": "2018-09-04T07:51:56.474686Z"
    }
   },
   "outputs": [],
   "source": [
    "OLS3_pre_list = get_pre_list(model_name='OLS3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.510783Z",
     "start_time": "2018-09-04T07:51:56.492234Z"
    }
   },
   "outputs": [],
   "source": [
    "ENet_pre_list = get_pre_list(model_name='ENet')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:50:46.452535Z",
     "start_time": "2018-09-04T12:50:46.428469Z"
    }
   },
   "outputs": [],
   "source": [
    "PCR_pre_list = get_pre_list(model_name='PCA')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.530836Z",
     "start_time": "2018-09-04T07:51:56.512789Z"
    }
   },
   "outputs": [],
   "source": [
    "GBRT_pre_list = get_pre_list(model_name='GBRT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.549385Z",
     "start_time": "2018-09-04T07:51:56.533342Z"
    }
   },
   "outputs": [],
   "source": [
    "RF_pre_list = get_pre_list(model_name='RF')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.567434Z",
     "start_time": "2018-09-04T07:51:56.550889Z"
    }
   },
   "outputs": [],
   "source": [
    "NN1_pre_list = get_pre_list(model_name='NN1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.586985Z",
     "start_time": "2018-09-04T07:51:56.569438Z"
    }
   },
   "outputs": [],
   "source": [
    "NN2_pre_list = get_pre_list(model_name='NN2')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.606036Z",
     "start_time": "2018-09-04T07:51:56.588993Z"
    }
   },
   "outputs": [],
   "source": [
    "NN3_pre_list = get_pre_list(model_name='NN3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T07:51:56.617074Z",
     "start_time": "2018-09-04T07:51:56.609043Z"
    }
   },
   "outputs": [],
   "source": [
    "y_real = np.array(top_1000_data_Y.loc['1988':])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## define D-M test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:50:54.325417Z",
     "start_time": "2018-09-04T12:50:54.321909Z"
    }
   },
   "outputs": [],
   "source": [
    "model_list = ['OLS3','OLS-3','PLS','PCR','ENet','GLM','RF','GBRT','NN1','NN2','NN3','NN4','NN5']\n",
    "removelist = ['PLS','GLM','NN4','NN5']\n",
    "for x in removelist:\n",
    "    model_list.remove(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:50:59.708800Z",
     "start_time": "2018-09-04T12:50:59.681728Z"
    }
   },
   "outputs": [],
   "source": [
    "length = len(model_list)\n",
    "higth = len(y_real)\n",
    "x = np.zeros(shape=(length,higth))\n",
    "\n",
    "x[0] = np.array(OLS_pre_list)\n",
    "x[1] = np.array(OLS3_pre_list) \n",
    "x[2] = np.array(PCR_pre_list) \n",
    "x[3] = np.array(ENet_pre_list)\n",
    "x[4] = np.array(RF_pre_list)\n",
    "x[5] = np.array(GBRT_pre_list)\n",
    "x[6] = np.array(NN1_pre_list)\n",
    "x[7] = np.array(NN2_pre_list)\n",
    "x[8] = np.array(NN3_pre_list)\n",
    "for j in range(length):\n",
    "    x[j] = np.square(x[j] - y_real)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:51:04.933660Z",
     "start_time": "2018-09-04T12:51:04.927143Z"
    }
   },
   "outputs": [],
   "source": [
    "def D_M_test_fun(x=x,num_year = 30,top_1000_data_Y=top_1000_data_Y):\n",
    "    matrix = np.zeros(shape=(length,length))\n",
    "    for j in range(length):\n",
    "        count_num = len(top_1000_data_Y.loc[str(1988+j)])\n",
    "        count_num2 = length - j - 1\n",
    "        for k in range(count_num2):\n",
    "            temp_list_01 = []\n",
    "            for i in range(num_year):\n",
    "                temp_result = sum((x[j][i*count_num:(i+1)*count_num] - x[j+k+1][i*count_num:(i+1)*count_num]))/count_num\n",
    "                temp_list_01.append(temp_result)\n",
    "            DM_test_p = np.mean(temp_list_01)/np.std(temp_list_01)\n",
    "            matrix[j][j+k+1] = DM_test_p \n",
    "    df =pd.DataFrame(matrix)\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:51:12.188904Z",
     "start_time": "2018-09-04T12:51:09.460167Z"
    }
   },
   "outputs": [],
   "source": [
    "df = D_M_test_fun(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-04T12:51:17.685486Z",
     "start_time": "2018-09-04T12:51:17.671450Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "      <th>1</th>\n",
       "      <th>2</th>\n",
       "      <th>3</th>\n",
       "      <th>4</th>\n",
       "      <th>5</th>\n",
       "      <th>6</th>\n",
       "      <th>7</th>\n",
       "      <th>8</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.213</td>\n",
       "      <td>-0.137</td>\n",
       "      <td>0.098</td>\n",
       "      <td>0.280</td>\n",
       "      <td>0.144</td>\n",
       "      <td>-0.128</td>\n",
       "      <td>0.075</td>\n",
       "      <td>0.174</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>-0.245</td>\n",
       "      <td>-0.033</td>\n",
       "      <td>0.161</td>\n",
       "      <td>0.011</td>\n",
       "      <td>-0.260</td>\n",
       "      <td>-0.137</td>\n",
       "      <td>-0.062</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.259</td>\n",
       "      <td>0.316</td>\n",
       "      <td>0.386</td>\n",
       "      <td>0.043</td>\n",
       "      <td>0.176</td>\n",
       "      <td>0.214</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.134</td>\n",
       "      <td>0.052</td>\n",
       "      <td>-0.220</td>\n",
       "      <td>-0.042</td>\n",
       "      <td>0.014</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>-0.153</td>\n",
       "      <td>-0.277</td>\n",
       "      <td>-0.209</td>\n",
       "      <td>-0.168</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>-0.248</td>\n",
       "      <td>-0.083</td>\n",
       "      <td>-0.026</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.178</td>\n",
       "      <td>0.233</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.145</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      0     1      2      3     4      5      6      7      8\n",
       "0 0.000 0.213 -0.137  0.098 0.280  0.144 -0.128  0.075  0.174\n",
       "1 0.000 0.000 -0.245 -0.033 0.161  0.011 -0.260 -0.137 -0.062\n",
       "2 0.000 0.000  0.000  0.259 0.316  0.386  0.043  0.176  0.214\n",
       "3 0.000 0.000  0.000  0.000 0.134  0.052 -0.220 -0.042  0.014\n",
       "4 0.000 0.000  0.000  0.000 0.000 -0.153 -0.277 -0.209 -0.168\n",
       "5 0.000 0.000  0.000  0.000 0.000  0.000 -0.248 -0.083 -0.026\n",
       "6 0.000 0.000  0.000  0.000 0.000  0.000  0.000  0.178  0.233\n",
       "7 0.000 0.000  0.000  0.000 0.000  0.000  0.000  0.000  0.145\n",
       "8 0.000 0.000  0.000  0.000 0.000  0.000  0.000  0.000  0.000"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "425.8px",
    "left": "934px",
    "right": "20px",
    "top": "140px",
    "width": "544.4px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
